<template>
	<div class="correction-container">
		<!-- 主Canvas用于显示和编辑 -->
		<div class="canvas-container">
			<canvas ref="secondCanvas" :width="canvasWidth" :height="canvasHeight"
				:style="{ width: canvasDisplayWidth + 'px', height: canvasDisplayHeight + 'px' }">
			</canvas>
		</div>

		<div class="container">
			<div class="outer-circle">
				<!-- 四个角点按钮 -->
				<div class="button-outer top-left">
					<button :style="{ transform: `rotate(${typeList[0].rotate}deg)` }"
						:class="[typeList[0].check ? 'active' : '']" @click="clickType(typeList[0], 0)">
						↗
					</button>
				</div>
				<div class="button-outer top-right">
					<button :style="{ transform: `rotate(${typeList[1].rotate}deg)` }"
						:class="[typeList[1].check ? 'active' : '']" @click="clickType(typeList[1], 1)">
						↗
					</button>
				</div>
				<div class="button-outer bottom-left">
					<button :style="{ transform: `rotate(${typeList[2].rotate}deg)` }"
						:class="[typeList[2].check ? 'active' : '']" @click="clickType(typeList[2], 2)">
						↗
					</button>
				</div>
				<div class="button-outer bottom-right">
					<button :style="{ transform: `rotate(${typeList[3].rotate}deg)` }"
						:class="[typeList[3].check ? 'active' : '']" @click="clickType(typeList[3], 3)">
						↗
					</button>
				</div>

				<div class="inner-circle">
					<!-- 方向控制按钮 -->
					<div class="button-inner top">
						<button @click="moveBtn('top', 10)">⇧⇧</button>
					</div>
					<div class="button-inner top-second">
						<button @click="moveBtn('top', 1)">⇧</button>
					</div>
					<div class="button-inner left">
						<button @click="moveBtn('left', 10)">⇧⇧</button>
					</div>
					<div class="button-inner left-second">
						<button @click="moveBtn('left', 1)">⇧</button>
					</div>
					<button @click="sendImage" :class="['center-button', { sending: isSending }]">投图</button>
					<div class="button-inner right">
						<button @click="moveBtn('right', 10)">⇧⇧</button>
					</div>
					<div class="button-inner right-second">
						<button @click="moveBtn('right', 1)">⇧</button>
					</div>
					<div class="button-inner bottom">
						<button @click="moveBtn('buttom', 10)">⇧⇧</button>
					</div>
					<div class="button-inner bottom-second">
						<button @click="moveBtn('buttom', 1)">⇧</button>
					</div>
				</div>
			</div>
		</div>
		<div class="bottom-buttons">
			<button @click="resetImgData">重置图片</button>
			<button @click="goBack">返回</button>
		</div>

		<!-- Toast组件 -->
    <div class="toast-container" v-if="toast.show">
      <div class="toast" :class="toast.type">
        {{ toast.message }}
      </div>
    </div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			// Canvas相关
			canvasWidth: 1280,
			canvasHeight: 720,
			mainCtx: null,
			isSending: false,
			deviceIP: '192.168.68.1', // 设备IP地址，可以从配置中获取或通过用户输入设置

			// 图片相关
			imageLoaded: false,
			originalImage: null,
			currentImage: null,

			// 变换相关
			rotation: 0,
			scale: 1,
			translateX: 0,
			translateY: 0,
			flipHorizontal: false,
			flipVertical: false,
			showGrid: false,
			currentFilter: null,

			// 四角校正相关
			ischeck: false,
			count: 50,
			selectedCorner: 0, // 默认选中左上角
			typeList: [
				{ text: '左上', value: 0, rotate: 270, check: true },
				{ text: '右上', value: 1, rotate: 0, check: false },
				{ text: '左下', value: 2, rotate: 180, check: false },
				{ text: '右下', value: 3, rotate: 90, check: false },
			],
			value: '1',
			imgRatio: 1, //默认图片比例
			copycorners: [], //图片初始点位拷贝
			idots: [], //图片分割点位
			corners: [
				{ x: 0, y: 0 }, // 左上
				{ x: 0, y: 0 }, // 右上
				{ x: 0, y: 0 }, // 左下
				{ x: 0, y: 0 }  // 右下
			],
			moveStep: 1, // 移动步长基础值
			imgSize: {
				left: 0,
				top: 0,
				width: 0,
				height: 0
			},
			imgData: null,
			 // Toast相关
      toast: {
        show: false,
        message: '',
        type: 'info', // 可以是 'info', 'success', 'warning', 'error'
        timeout: null
      }
		};
	},
	computed: {
		canvasDisplayWidth() {
			// 获取当前视口宽度
			const viewportWidth = Math.min(window.innerWidth, this.canvasWidth);
			// 如果视口宽度小于Canvas宽度，按比例缩放
			if (viewportWidth < this.canvasWidth) {
				return viewportWidth; // 留出一些边距
			}
			return this.canvasWidth;
		},
		canvasDisplayHeight() {
			// 保持宽高比
			const ratio = this.canvasHeight / this.canvasWidth;
			return this.canvasDisplayWidth * ratio;
		}
	},

	beforeDestroy() {
		// 移除窗口大小变化监听
		this.gotocornerpostions(0)
		window.removeEventListener('resize', this.handleResize);
	},
	mounted() {
		document.title = '影描-四角校正投图';
		this.initCanvas();
		// 从localStorage获取图像数据
		const imageUrl = localStorage.getItem('correctionImage');
		const savedRotation = localStorage.getItem('imageRotation');
    if (savedRotation) {
        this.rotation = parseInt(savedRotation);
    }
		if (imageUrl) {
			this.createImageObject(imageUrl)
				.then(img => {
					this.originalImage = img;
					this.currentImage = img;
					this.imageLoaded = true;
					this.drawImageToCanvas();
					this.initCorners();

					const savedPositions = localStorage.getItem('savedCornerPositions');
			
					if (savedPositions) {
						const parsedPositions = JSON.parse(savedPositions);
						const restoredCorners = parsedPositions.corners;
						
						// 检查恢复的角点是否重叠
						if (!this.checkCornersOverlap(restoredCorners)) {
							this.corners = restoredCorners;
							
							setTimeout(() => {
								this.moveBtn('right', 0);
							}, 500);
						} else {
							console.log('检测到角点重叠，放弃恢复保存的角点位置');
							// 可以添加一个提示
							this.showToast('角点位置异常，已重置', 'warning');
							// 不需要额外操作，因为initCorners已经设置了默认角点位置
						}
					}
          //新增2025.11.01
          this.resetImgData()
				})
				.catch(error => {
					console.error('加载图片失败:', error);
					this.showToast('加载图片失败', 'error');
				});

		}
		// 添加窗口大小变化监听
		window.addEventListener('resize', this.handleResize);
		// 禁用双击放大
		document.addEventListener('touchstart', function (event) {
			if (event.touches.length > 1) {
				event.preventDefault();
			}
		}, { passive: false });

		let lastTouchEnd = 0;
		document.addEventListener('touchend', function (event) {
			const now = Date.now();
			if (now - lastTouchEnd < 300) {
				event.preventDefault();
			}
			lastTouchEnd = now;
		}, { passive: false });

	},

	methods: {

		// 在methods中添加一个新方法来检查角点是否重叠
checkCornersOverlap(corners) {
  // 定义一个最小距离阈值，如果两个角点之间的距离小于这个值，则认为它们重叠
  const minDistance = 20; // 可以根据实际情况调整
  
  // 检查任意两个角点之间的距离
  for (let i = 0; i < corners.length; i++) {
    for (let j = i + 1; j < corners.length; j++) {
      const dx = corners[i].x - corners[j].x;
      const dy = corners[i].y - corners[j].y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < minDistance) {
        return true; // 发现重叠的角点
      }
    }
  }
  
  return false; // 没有重叠的角点
},

		// 添加Toast方法
    showToast(message, type = 'info', duration = 2000) {
      // 清除之前的定时器
      if (this.toast.timeout) {
        clearTimeout(this.toast.timeout);
      }
      
      // 设置新的Toast
      this.toast.message = message;
      this.toast.type = type;
      this.toast.show = true;
      
      // 设置自动隐藏
      this.toast.timeout = setTimeout(() => {
        // 添加一个监听器来处理动画结束事件
        const toastElement = document.querySelector('.toast');
        if (toastElement) {
          toastElement.addEventListener('animationend', (e) => {
            // 只有当是fadeOut动画结束时才隐藏元素
            if (e.animationName === 'fadeOut') {
              this.toast.show = false;
            }
          }, { once: true });
          
          // 添加一个类来触发淡出动画
          toastElement.classList.add('toast-hiding');
        } else {
          // 如果找不到元素，直接隐藏
          this.toast.show = false;
        }
      }, duration - 300); // 提前300ms开始准备动画
    },
		/**
		 * 初始化Canvas
		 */
		initCanvas() {
			try {
				const canvas = this.$refs.secondCanvas;
				if (!canvas) {
					console.error('无法获取Canvas元素');
					return;
				}
				this.mainCtx = canvas.getContext('2d');
				if (!this.mainCtx) {
					console.error('无法获取Canvas上下文');
					return;
				}
				console.log('Canvas初始化完成');
			} catch (error) {
				console.error('初始化Canvas失败:', error);
			}
		},

		/**
		 * 创建图片对象
		 */
		createImageObject(src) {
			return new Promise((resolve, reject) => {
				const img = new Image();
				img.crossOrigin = 'anonymous'; // 允许跨域加载图片
				img.onload = () => {
					console.log('图片加载成功:', img.width, 'x', img.height);
					resolve(img);
				};
				img.onerror = (e) => {
					console.error('图片加载失败:', e);
					reject(new Error('图片加载失败'));
				};
				img.src = src;
			});
		},

		/**
		 * 绘制图片到Canvas
		 */
		drawImageToCanvas() {
			if (!this.imageLoaded || !this.currentImage || !this.mainCtx) {
				console.log('无法绘制图片:', {
					imageLoaded: this.imageLoaded,
					hasCurrentImage: !!this.currentImage,
					hasMainCtx: !!this.mainCtx
				});
				return;
			}

			try {
				// 清除Canvas
				this.mainCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

				console.log('绘制图片:', {
					imgWidth: this.currentImage.width,
					imgHeight: this.currentImage.height,
					canvasWidth: this.canvasWidth,
					canvasHeight: this.canvasHeight,
					scale: this.scale,
					rotation: this.rotation,
					flipH: this.flipHorizontal,
					flipV: this.flipVertical
				});

				// 保存当前状态
				this.mainCtx.save();

				// 移动到Canvas中心
				this.mainCtx.translate(this.canvasWidth / 2 + this.translateX, this.canvasHeight / 2 + this.translateY);

				// 旋转
				// this.mainCtx.rotate((this.rotation * Math.PI) / 180);

				// 翻转
				this.mainCtx.scale(
					this.flipHorizontal ? -this.scale : this.scale,
					this.flipVertical ? -this.scale : this.scale
				);

				// 计算图片绘制尺寸和位置
				const imgWidth = this.currentImage.width;
				const imgHeight = this.currentImage.height;

				// 计算缩放比例以适应Canvas
				const ratio = Math.min(this.canvasWidth / imgWidth, this.canvasHeight / imgHeight);
				const scaledWidth = imgWidth * ratio;
				const scaledHeight = imgHeight * ratio;

				// 绘制图片（居中）
				this.mainCtx.drawImage(
					this.currentImage,
					-scaledWidth / 2,
					-scaledHeight / 2,
					scaledWidth,
					scaledHeight
				);

				// 应用滤镜
				if (this.currentFilter) {
					this.applyFilterToCanvas();
				}

				// 恢复状态
				this.mainCtx.restore();

				// 保存图像数据用于重置
				this.imgData = this.mainCtx.getImageData(0, 0, this.canvasWidth, this.canvasHeight);

				console.log('Canvas 绘制完成');
			} catch (error) {
				console.error('绘制图片失败:', error);
			}
		},

		// 选择角点
		clickType(clickItem, index) {
			this.typeList = this.typeList.map((item) => {
				item.check = clickItem.value === item.value;
				return item;
			});
			this.selectedCorner = clickItem.value;

      this.moveBtn('',0)
		},

		// 移动角点
		moveBtn(direction, value, isCanvasPoint = true) {
			if (this.selectedCorner === null) {
				this.showToast('请先选择一个角点', 'error');
				return;
			}

			// 根据value值计算实际移动步长
			this.value = value;
			const actualStep = parseInt(this.value) * this.moveStep;
			const corner = this.corners[this.selectedCorner];

			// 移动选中的角点
			switch (direction) {
				case 'top':
					corner.y = Math.max(0, Math.min(corner.y - actualStep, this.canvasHeight));
					break;
				case 'right':
					corner.x = Math.max(0, Math.min(corner.x + actualStep, this.canvasWidth));
					break;
				case 'left':
					corner.x = Math.max(0, Math.min(corner.x - actualStep, this.canvasWidth));
					break;
				case 'buttom':
					corner.y = Math.max(0, Math.min(corner.y + actualStep, this.canvasHeight));
					break;
			}

			// 清除画布并重绘
			this.mainCtx.putImageData(this.imgData, 0, 0);

			// 绘制变形后的四边形
			this.mainCtx.beginPath();
			this.mainCtx.moveTo(this.corners[0].x, this.corners[0].y);
			this.mainCtx.lineTo(this.corners[1].x, this.corners[1].y);
			this.mainCtx.lineTo(this.corners[3].x, this.corners[3].y);
			this.mainCtx.lineTo(this.corners[2].x, this.corners[2].y);
			this.mainCtx.closePath();
			this.mainCtx.strokeStyle = 'rgba(41, 121, 255, 0.3)';
			this.mainCtx.lineWidth = 0.1;
			this.mainCtx.stroke();

			this.render();

			
			// 绘制角点
      if (isCanvasPoint){
       // 绘制角点
				this.corners.forEach((corner, index) => {
					this.mainCtx.beginPath();
					this.mainCtx.arc(corner.x, corner.y, 10, 0, 2 * Math.PI);
					this.mainCtx.fillStyle = this.selectedCorner === index ? 'red' : 'blue';
					this.mainCtx.fill();
					this.mainCtx.closePath();
				});
      }
      this.gotocornerpostions(parseInt(this.selectedCorner) + 2);
		},

		// 初始化角点位置
		initCorners() {

			// 计算图片绘制尺寸和位置
			const imgWidth = this.currentImage.width;
			const imgHeight = this.currentImage.height;

			// 计算缩放比例以适应Canvas
			const ratio = Math.min(this.canvasWidth / imgWidth, this.canvasHeight / imgHeight);
			const scaledWidth = imgWidth * ratio;
			const scaledHeight = imgHeight * ratio;

			// 计算图片在Canvas中的位置（居中）
			const left = (this.canvasWidth - scaledWidth) / 2;
			const top = (this.canvasHeight - scaledHeight) / 2;

			this.imgSize = {
				left: left,
				top: top,
				width: scaledWidth,
				height: scaledHeight
			};

			 // 设置正确的imgRatio值
    this.imgRatio = ratio;

			this.corners = [
				{ x: left, y: top }, // 左上
				{ x: left + scaledWidth, y: top }, // 右上
				{ x: left, y: top + scaledHeight }, // 左下
				{ x: left + scaledWidth, y: top + scaledHeight } // 右下
			];

			this.copycorners = JSON.parse(JSON.stringify(this.corners));
			this.idots = this.rectsplit(this.count, this.copycorners[0], this.copycorners[1], this.copycorners[3], this.copycorners[2]);
		  setTimeout(()=>{
        this.gotocornerpostions(1);
			},500)
		},
		// 四角校正点位置更新方法
		gotocornerpostions(state) {
			// 计算缩放比例
			const scale = 1; // Web版本不需要缩放比例，直接使用Canvas坐标
			// 获取四个角点的坐标
			const cornerPositions = this.corners.map(corner => ({
				x: Math.round(corner.x),
				y: Math.round(corner.y)
			}));
			// 构建发送数据
			const cornerData = {
				leftTop: cornerPositions[0],
				rightTop: cornerPositions[1],
				leftBottom: cornerPositions[2],
				rightBottom: cornerPositions[3]
			};
			console.log('Corner positions:', JSON.stringify(cornerData));
			// 获取各个角点的坐标值
			const x1 = parseInt(this.corners[0].x);
			const y1 = parseInt(this.corners[0].y);
			const x2 = parseInt(this.corners[1].x);
			const y2 = parseInt(this.corners[1].y);
			const x3 = parseInt(this.corners[2].x);
			const y3 = parseInt(this.corners[2].y);
			const x4 = parseInt(this.corners[3].x);
			const y4 = parseInt(this.corners[3].y);

			console.log('校正信息:', state, x1, y1, x2, y2, x3, y3, x4, y4);
		

			// 构建GET请求参数
			const params = `x1=${x1}&y1=${y1}&x2=${x2}&y2=${y2}&x3=${x3}&y3=${y3}&x4=${x4}&y4=${y4}&dir=${this.selectedCorner}&state=${state}`;
			console.log('发送参数:', params);

			// 使用fetch发送GET请求
			fetch(`/correct_pos?${params}`, {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json'
				}
			})
			.then(response => response.json())
			.then(data => {
				console.log('校正信息返回:', data);
			}).catch(error => {
				console.error('发送校正信息失败:', error);
			});
		},
		// 将四边形分割成n的n次方份
		rectsplit(n, a, b, c, d) {
			// ad 向量方向 n 等分
			const ad_x = (d.x - a.x) / n;
			const ad_y = (d.y - a.y) / n;
			// bc 向量方向 n 等分
			const bc_x = (c.x - b.x) / n;
			const bc_y = (c.y - b.y) / n;

			const ndots = [];
			let x1, y1, x2, y2, ab_x, ab_y;

			// 左边点递增，右边点递增，获取每一次递增后的新的向量，继续 n 等分
			for (let i = 0; i <= n; i++) {
				// 获得 ad 向量 n 等分后的坐标
				x1 = a.x + ad_x * i;
				y1 = a.y + ad_y * i;
				// 获得 bc 向量 n 等分后的坐标
				x2 = b.x + bc_x * i;
				y2 = b.y + bc_y * i;

				for (let j = 0; j <= n; j++) {
					// ab 向量为：[x2 - x1 , y2 - y1]，所以 n 等分后的增量为除于 n
					ab_x = (x2 - x1) / n;
					ab_y = (y2 - y1) / n;

					ndots.push({
						x: x1 + ab_x * j,
						y: y1 + ab_y * j,
					});
				}
			}

			return ndots;
		},

		// 绘制变形图片
		render() {
			// 清除画布
      this.mainCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			const ndots = this.rectsplit(this.count, this.corners[0], this.corners[1], this.corners[3], this.corners[2]);

			// 设置图像合成模式
			this.mainCtx.globalCompositeOperation = 'source-over';
			// 添加抗锯齿和平滑处理
			this.mainCtx.imageSmoothingEnabled = true;
			this.mainCtx.imageSmoothingQuality = 'high';

			ndots.forEach((d, i) => {
				// 获取平行四边形的四个点
				const dot1 = ndots[i];
				const dot2 = ndots[i + 1];
				const dot3 = ndots[i + this.count + 2];
				const dot4 = ndots[i + this.count + 1];

				// 获取初始平行四边形的四个点
				const idot1 = this.idots[i];
				const idot2 = this.idots[i + 1];
				const idot3 = this.idots[i + this.count + 2];
				const idot4 = this.idots[i + this.count + 1];

				if (dot2 && dot3 && i % (this.count + 1) < this.count) {
					// 绘制三角形的下半部分
					this.renderImage(idot3, dot3, idot2, dot2, idot4, dot4, idot1);

					// 绘制三角形的上半部分
					this.renderImage(idot1, dot1, idot2, dot2, idot4, dot4, idot1);
				}
			});
		},

		// 渲染图像变换
		renderImage(arg_1, _arg_1, arg_2, _arg_2, arg_3, _arg_3, vertex) {
			this.mainCtx.save();
			this.mainCtx.clip('evenodd');

			if (this.currentImage) {
				// 传入变换前后的点坐标，计算变换矩阵
				const result = this.getMatrix.apply(this, arguments);
				// 变形
				this.mainCtx.transform(result.a, result.b, result.c, result.d, result.e, result.f);

				const w = this.currentImage.width / this.count;
				const h = this.currentImage.height / this.count;
				// 根据旋转角度设置不同的offset值
        const offset = (this.rotation === 90 || this.rotation === 270) ? 2 : 0.5;

				// 绘制图片
				this.mainCtx.drawImage(
					this.currentImage,
					(vertex.x - this.idots[0].x) / this.imgRatio - offset,
					(vertex.y - this.idots[0].y) / this.imgRatio - offset,
					w / this.imgRatio + offset * 2,
					h / this.imgRatio + offset * 2,
					vertex.x - offset,
					vertex.y - offset,
					w + offset * 2,
					h + offset * 2
				);
			}

			this.mainCtx.restore();
		},

		// 计算变换矩阵
		getMatrix(arg_1, _arg_1, arg_2, _arg_2, arg_3, _arg_3) {
			// 传入x值解第一个方程 即 X = ax + cy + e 求ace
			const arr1 = [arg_1.x, arg_1.y, 1, _arg_1.x];
			const arr2 = [arg_2.x, arg_2.y, 1, _arg_2.x];
			const arr3 = [arg_3.x, arg_3.y, 1, _arg_3.x];

			const result = this.equation(arr1, arr2, arr3);

			// 传入y值解第二个方程 即 Y = bx + dy + f 求 bdf
			arr1[3] = _arg_1.y;
			arr2[3] = _arg_2.y;
			arr3[3] = _arg_3.y;

			const result2 = this.equation(arr1, arr2, arr3);

			// 获得a、c、e
			const a = result.x;
			const c = result.y;
			const e = result.z;

			// 获得b、d、f
			const b = result2.x;
			const d = result2.y;
			const f = result2.z;

			return { a, b, c, d, e, f };
		},

		// 解三元一次方程
		equation(arr1, arr2, arr3) {
			const a1 = +arr1[0];
			const b1 = +arr1[1];
			const c1 = +arr1[2];
			const d1 = +arr1[3];

			const a2 = +arr2[0];
			const b2 = +arr2[1];
			const c2 = +arr2[2];
			const d2 = +arr2[3];

			const a3 = +arr3[0];
			const b3 = +arr3[1];
			const c3 = +arr3[2];
			const d3 = +arr3[3];

			// 添加小的偏移量避免除以零
			const epsilon = 1e-10;
			const b2Adjusted = Math.abs(b2) < epsilon ? epsilon : b2;
			const b3Adjusted = Math.abs(b3) < epsilon ? epsilon : b3;

			// 分离计算单元
			const m1 = c1 - (b1 * c2 / b2Adjusted);
			const m2 = c2 - (b2Adjusted * c3 / b3Adjusted);
			const m3 = d2 - (b2Adjusted * d3 / b3Adjusted);
			const m4 = a2 - (b2Adjusted * a3 / b3Adjusted);
			const m5 = d1 - (b1 * d2 / b2Adjusted);
			const m6 = a1 - (b1 * a2 / b2Adjusted);

			// 检查中间计算结果
			if (isNaN(m1) || isNaN(m2) || isNaN(m3) || isNaN(m4) || isNaN(m5) || isNaN(m6)) {
				console.error("Intermediate values are NaN");
				return { x: 0, y: 0, z: 0 };
			}
			if (!isFinite(m1) || !isFinite(m2) || !isFinite(m3) || !isFinite(m4) || !isFinite(m5) || !isFinite(m6)) {
				console.error("Intermediate values are Infinity or -Infinity");
				return { x: 0, y: 0, z: 0 };
			}

			// 计算xyz
			const denominator = (m1 / m2) * m4 - m6;
			if (Math.abs(denominator) < epsilon) {
				console.error("Denominator is too small to avoid division by zero");
				return { x: 0, y: 0, z: 0 };
			}

			const x = ((m1 / m2) * m3 - m5) / denominator;
			const z = (m3 - m4 * x) / m2;
			const y = (d1 - a1 * x - c1 * z) / b1;

			return { x, y, z };
		},

		// 发送图像
		sendImage() {
			if (this.isSending) return;
			this.isSending = true;

			if (!this.imageLoaded) {
				this.showToast('请先加载图片', 'error');
				this.isSending = false;
				return;
			}
			this.moveBtn('buttom',0,false)
      try {

        // 获取Canvas图像数据
        const canvas = this.$refs.secondCanvas;

        // 使用toDataURL替代toBlob，解决移动端兼容性问题
        const dataURL = canvas.toDataURL('image/jpeg', 0.9);
        // 将base64转换为Blob
        const base64ToBlob = (dataURL) => {
          const arr = dataURL.split(',');
          const mime = arr[0].match(/:(.*?);/)[1];
          const bstr = atob(arr[1]);
          let n = bstr.length;
          const u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          return new Blob([u8arr], { type: mime });
        };

        const blob = base64ToBlob(dataURL);

        // 创建FormData
        const formData = new FormData();
        formData.append('file', blob, 'image.jpg'); // 修改文件名为.jpg

        // 使用相对路径，不依赖特定IP
        // fetch('http://192.168.3.218/playimg', {
        fetch(`/playimg`, {
          method: 'POST',
          body: formData
        }).then(response => {
          if (!response.ok) {
            throw new Error(`HTTP错误，状态码: ${response.status}`);
          }
          return response.json();
        })
            .then(data => {
              console.log(data);
							this.showToast('图片已成功发送到投影设备！', 'success');
            })
            .catch(error => {
              console.error('上传失败', error);
              if (error.message && error.message.includes('net::ERR_CONNECTION')) {
                console.log('网络连接问题，请检查网络连接');
								this.showToast('网络连接问题，请检查网络连接', 'error');
              } else if (error.message && error.message.includes('404')) {
                console.log('服务器未找到上传地址');
								this.showToast('服务器未找到上传地址', 'error');
              } else {
                console.log('其他错误：', error);
								this.showToast('发送失败，请重试', 'error');
              }
            })
            .finally(() => {
              setTimeout(() => {
                this.isSending = false; // 2秒后重新启用按钮
                console.log("Sending enabled again.");
              }, 1000);
            });

      } catch (error) {
        console.error('准备图片数据失败:', error);
				this.showToast('发送失败，请重试', 'error');
        this.isSending = false;
      }
		},

		// 重置图像数据
		resetImgData() {
			if (!this.imageLoaded) {
				this.showToast('请先加载图片', 'error');
				return;
			}
			// 恢复原始图像数据
			this.mainCtx.putImageData(this.imgData, 0, 0);
			// 重置角点位置
			this.initCorners();
		},

		// 返回上一页
		goBack() {
			// 清除旋转角度信息
			const savedCorners = {
				corners: this.corners
			};
			localStorage.setItem('savedCornerPositions', JSON.stringify(savedCorners));
			console.log('已保存角点位置', JSON.stringify(savedCorners));

      localStorage.removeItem('imageRotation');
			this.$emit('navigate', 'home');
		}
	}
};
</script>

<style scoped>
html, body {
  touch-action: manipulation;
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
.correction-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 100%;
	height: 100%;
	background-color: #f5f5f5;
	overflow-x: hidden;
}

.canvas-container {
	width: 100%;
	overflow-x: auto;
	max-width: 100%;
	display: flex;
	justify-content: center;
}

.image-canvas {
	border: 1px solid #ccc;
}

.container {
	display: flex;
	flex-direction: column;
	align-items: center;
	border: 1px solid #000;
	margin-top: 20px;
}

.outer-circle {
	position: relative;
	width: 340px;
	height: 340px;
	border-radius: 50%;
	background-color: #e0e0e0;
	display: flex;
	justify-content: center;
	align-items: center;
}

.button-outer {
	position: absolute;
	width: 40px;
	height: 40px;
}

.top-left {
	top: 20px;
	left: 20px;
}

.top-right {
	top: 20px;
	right: 20px;
}

.bottom-left {
	bottom: 20px;
	left: 20px;
}

.bottom-right {
	bottom: 20px;
	right: 20px;
}

.button-outer button {
	width: 100%;
	height: 100%;
	border-radius: 50%;
	border: none;
	background-color: #fff;
	font-size: 20px;
	cursor: pointer;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 0;
	line-height: 1;
}

.button-outer button.active {
	background-color: #ba0100;
	color: white;
}

.inner-circle {
	position: relative;
	width: 260px;
	height: 260px;
	border-radius: 50%;
	background-color: #f0f0f0;
	display: flex;
	justify-content: center;
	align-items: center;
}

.button-inner {
	position: absolute;
	width: 40px;
	height: 40px;
}

.top {
	top: 10px;
	left: 50%;
	transform: translateX(-50%);
}

.top-second {
	top: 60px;
	left: 50%;
	transform: translateX(-50%);
}

.left {
	left: 10px;
	top: 50%;
	transform: translateY(-50%) rotate(-90deg);

}

.left-second {
	left: 60px;
	top: 50%;
	transform: translateY(-50%) rotate(-90deg);
}

.right {
	right: 10px;
	top: 50%;
	transform: translateY(-50%) rotate(90deg);
}

.right-second {
	right: 60px;
	top: 50%;
	transform: translateY(-50%) rotate(90deg);
}

.bottom {
	bottom: 10px;
	left: 50%;
	transform: translateX(-50%) rotate(180deg);
}

.bottom-second {
	bottom: 60px;
	left: 50%;
	transform: translateX(-50%) rotate(180deg);
}

.button-inner button {
	width: 100%;
	height: 100%;
	border-radius: 50%;
	border: none;
	background-color: #fff;
	font-size: 16px;
	cursor: pointer;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 0;
	line-height: 1;
}

.center-button {
	width: 60px;
	height: 60px;
	border-radius: 50%;
	border: none;
	background-color: #4CAF50;
	color: white;
	font-size: 16px;
	cursor: pointer;
}

.center-button.sending {
	background-color: #f44336;
}

.bottom-buttons {
	display: flex;
	justify-content: space-around;
	width: 100%;
	margin-top: 20px;
}

.bottom-buttons button {
	width: 150px !important;
	margin: 8px;
	height: 40px !important;
	background-color: #fff;
	border-radius: 5px;
	border: black 1px solid;
	line-height: 40px !important;
	font-size: 14px;
	text-align: center;
}
/* Toast样式 */
.toast-container {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  pointer-events: none;
}

.toast {
  padding: 10px 20px;
  border-radius: 4px;
  color: white;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  animation: fadeIn 0.3s;
  white-space: nowrap;
}

.toast.toast-hiding {
  animation: fadeOut 0.3s forwards;
}

.toast.info {
  background-color: #2196F3;
}

.toast.success {
  background-color: #4CAF50;
}

.toast.warning {
  background-color: #FF9800;
}

.toast.error {
  background-color: #F44336;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fadeOut {
  from { opacity: 1; transform: translateY(0); }
  to { opacity: 0; transform: translateY(-20px); }
}
</style>